import { requestClient } from '#/api/request'

// 查询计量间返回值
interface ListMeteringMeteringStationResult {
  rows: any;
  total: number;
}
//添加计量间参数
export interface AddMeteringStationParams extends Record<string, any> {
  stationCode: string;
  stationName: string;
  location: string;
  operationArea:number;
  block:number;
  totalInterfaces:number;
  userdInterfaces:number;
  reservedInterfaces:number;
  downstreamDehydrationStation:string;
  capacity:number;
  remark: string;
}

//修改计量间参数
export interface EditMeteringStationParams extends Record<string, any> {
  stationCode: string;
  stationName: string;
  location: string;
  operationArea:number;
  block:number;
  totalInterfaces:number;
  userdInterfaces:number;
  reservedInterfaces:number;
  downstreamDehydrationStation:string;
  capacity:number;
  remark: string;
}
//在地图上展示计量间
export const getMeteringStationsByGis = async () => {
  const response = await requestClient.get('/manage/measurementroom/list');
  const data = response.rows;
  const mappedResult = data.map((row: any) => {
    const location = row.location;
    let locationFormatted: [number,number] | undefined = undefined;
  
    if (location && location.startsWith('POINT')) {
      const [longitude,latitude] = location.match(/-?\d+(\.\d+)?/g)?.map(Number) || [];
      locationFormatted = [longitude,latitude];
    }
    
    return {
      ...row,
      location: locationFormatted,
    };
  });
  return mappedResult;
}

// 查询计量间列表
export const listMeteringStation = async (params: {
  pageNum: number;
  pageSize: number;
  stationCode?: string;
  stationName?: string;
}) => {
  const response = await requestClient.get('/manage/measurementroom/list', { params });
  const data = response.rows; // 提取 rows 字段

  const total = response.total;

  const result = data;

  const mappedResult = result.map((row: any) => {
    const location = row.location;
    let locationFormatted: string | undefined = undefined;

    if (location && location.startsWith('POINT')) {
      const [longitude, latitude] = location.match(/-?\d+(\.\d+)?/g)?.map(Number) || [];
      locationFormatted = `经度: ${longitude}, 纬度: ${latitude}`;
    }
    return {
      ...row,
      status: row.status === 1 ? '正常' : '冻结',
      location: locationFormatted,
    };
  });
  return {
    items: mappedResult,
    total: total,
  };
};

// 查询计量间详细
export async function getMeteringStation(id: number) {
  return requestClient.get(`/manage/measurementroom/${id}`);
}

// 新增计量间
export async function addMeteringStation(data:AddMeteringStationParams) {
  await requestClient.post('/manage/measurementroom', data);
}

// 修改计量间
export async function updateMeteringStation(data: EditMeteringStationParams) {
  requestClient.put('/manage/measurementroom', data);
}

// 删除计量间
export async function delMeteringStation(id: number) {
  requestClient.delete(`/manage/measurementroom/${id}`);
}
